<?php

class ProductController extends Controller {

    public function actionList() {
        $this->pageTitle = 'List of products ';
        
        // query products list
        $catid = Yii::app()->request->getQuery('categoryid');

        $productModel = new Product;
        $criteria;
        if ($catid !== null) {
            $criteria = $productModel->createCriteria('by_category_list', array('cat_id' => $catid));
        }
        $data = $productModel->listProducts($criteria);

        // create breadcrumbs
        $catname;
        foreach ($this->categories as $category) {
            if ($category['childCategories'] === null) {
                if ($category['id'] == $catid) {
                    $catname = $category['name'];
                }
            } else {
                $childCategories = $category['childCategories'];
                if ($category['id'] == $catid) {
                    $catname = $category['name'];
                    $subCategories = array();
                    foreach ($childCategories as $childCategory) {                     
                        $childCategory['childCategories'] = null;
                        $subCategories[] = $childCategory;
                    }
                    $this->subCategories = $subCategories;
                } else {
                    foreach ($childCategories as $childCategory) {
                        if ($childCategory['id'] == $catid) {
                            $catname = $childCategory['name'];
                            break;
                        }
                    }
                }
            }
            if (isset($catname)) {
                break;
            }
        }
        if (isset($catname)) {
            // $this->breadcrumbs[$catname] = $this->createUrl('product/list');
            $this->breadcrumbs[] = $catname;
            $this->pageTitle = $catname;
        }

        // render 'list' view'
        $data['thumbnail_size'] = array(180, 135);
        $this->render('list', $data);
    }

    public function actionAjaxView() {
        if (!Yii::app()->request->isAjaxRequest) {
            return;
        }
        if (!isset($_GET['id'])) {
            throw new CHttpException(404, Yii::t('default', 'Requested page does not exist.'));
        }

        // get id from GET parameters
        $id = Yii::app()->request->getQuery('id');

        // find the product by ID
        $product = Product::model()->findByPk($id);
        if ($product == null) {
            throw new CHttpException(404, Yii::t('default', 'Requested page does not exist.'));
        }

        // get ProductDetail object by lanuage
        $detail = $product->getProductDetail(Yii::app()->language);

        // get ProductImage object
        $images = $product->productImages;

        // create data model
        $data = array();
        if ($detail != null && $images != null) {
            $data['pid'] = $product->id;
            $data['pname'] = $detail->name;
            $data['pseokey'] = $detail->seokey;
            $data['pcontent'] = $detail->content;
            $data['pprice'] = $product->price;
            $data['ppromotion'] = $product->promotion;
            // all image url with full path
            $paths = array();
            $uploadPath = Yii::app()->getBaseUrl(true) . '/';
            foreach ($images as $img) {
                $paths[] = $uploadPath . $img->path;
            }
            $data['pimgages'] = $paths;
        }

        $this->renderPartial('ajaxView', $data, false, true);
    }

    public function actionView() {
        $this->metaDescription = 'This page referrals to customers need buy product with detail and any informations related to it';
        
        $id = Yii::app()->request->getQuery('id');
        if ($id == null) {
            throw new CHttpException(404, Yii::t('default', 'Requested page does not exist.'));
        }

        $product = Product::model()->findByPk($id);
        if ($product == null) {
            throw new CHttpException(404, Yii::t('default', 'Requested page does not exist.'));
        }

        $productDetail = $product->getProductDetail(Yii::app()->language);
        $productImages = $product->productImages;

        // create breadcrumbs and pageTile
        $this->pageTitle = '';
        if ($product->category_id != null) {
            $cat = Category::model()->findByPk($product->category_id);
            $catname;
            if ($cat != null) {
                foreach ($cat->categoryDetails as $categoryDetail) {
                    if ($categoryDetail->language == Yii::app()->language) {
                        $catname = $categoryDetail->name;
                        break;
                    }
                }
            }

            if (isset($catname)) {
                $this->breadcrumbs[$catname] = $this->createUrl('product/list', array('categoryid' => $cat->id, 'categorykey'=> $cat->categoryDetail()->seokey, 'page' => 1));
                $this->pageTitle .= $catname . ' - ';
            }
        }
        $this->breadcrumbs[] = $productDetail->name;
        $this->pageTitle .= $productDetail->name;

        // render view page
        if ($productDetail != null && $productImages != null) {
            $this->render('view', array(
                'product' => $product,
                'productDetail' => $productDetail,
                'productImages' => $productImages,
            ));
        }
    }

    public function actionSearch() {
        $productSearch = new Search;
        if (isset($_GET['Search'])) {
            $productSearch->attributes = $_GET['Search'];
            $keyWord = $productSearch->keyWord;
            $pages = new CMyPagination;
            $products = array();
            if (strlen($keyWord) > 0) {
                $criteria = new CDbCriteria;
                $criteria->distinct = true;
                $criteria->addCondition('status =:status');
                $searchCondition = '';
                if ($productSearch->searchByName) {
                    $searchCondition = 'd.name like :keyWord';
                }
                if ($productSearch->searchByContent) {
                    if ($searchCondition == '') {
                        $searchCondition = 'd.content like :keyWord';
                    } else {
                        $searchCondition = ' OR d.content like :keyWord';
                    }
                }
                if (!$productSearch->searchByName && !$productSearch->searchByContent) {
                    $searchCondition = 'd.name like :keyWord OR d.content like :keyWord';
                }
                if ($searchCondition != '') {
                    $searchCondition = ' AND (' . $searchCondition . ')';
                }
                $criteria->join = 'INNER JOIN product_detail d ON t.id=d.product_id ' . $searchCondition;
                $criteria->params = array(':status' => 'yes', ':keyWord' => '%' . $keyWord . '%'); //
                //pager
                $itemCount = Product::model()->count($criteria);
                $pages->setItemCount($itemCount);
                $pages->setPageSize(20);
                $pages->applyLimit($criteria);

                $results = Product::model()->findAll($criteria);
                $language = Yii::app()->language;
                if (count($results) > 0) {
                    foreach ($results as $p) {
                        $product = array();
                        $product['id'] = $p->id;
                        $product['price'] = $p->price;
                        $product['name'] = '';
                        $product['url'] = $p->getUrl();
                        $product['content'] = '';
                        $product['image'] = '';

                        if (count($p->productDetails) > 0) {
                            $index = 0;
                            if ($language == 'vi') {
                                $index = 1;
                            }
                            $product['name'] = $p->productDetails[$index]->name;
                            $product['seokey'] = $p->productDetails[$index]->seokey;
                            $product['content'] = $p->productDetails[$index]->content;
                        }
                        if (count($p->productImages) > 0) {
                            $product['image'] = Yii::app()->getBaseUrl(true) . '/' . $p->productImages[0]->path;
                        }
                        $products[] = $product;
                    }
                }
            }
            $thumbnail_size = array(180, 135);
            $this->breadcrumbs[] = Yii::t('default', 'Search');
            $this->pageTitle = Yii::t('default', 'Need buy Search');
            $this->metaDescription = 'This page shows results of customers search';
                    
            $this->render('list', array(
                'pages' => $pages,
                'thumbnail_size' => $thumbnail_size,
                'products' => $products,
            ));
        }
    }

}